package com.qys.controller.down;

import com.qys.common.utils.RSAUtil;
import com.qys.controller.entiry.FinalURL;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import org.apache.log4j.Logger;

/**
 * Created by fangc on 2019-10-24 00:03
 */
@Controller
public class DownLoadController {
    private final Logger logger = Logger.getLogger(DownLoadController.class);
    @GetMapping(path = "/file/download.do")
    @ResponseBody
    private JSONObject down(HttpServletRequest request, HttpServletResponse response) {
        String uuid = request.getParameter("uuid");
        CloseableHttpClient httpClient = HttpClients.createDefault();
        InputStream in = null;
        HttpGet httpGet = null;
        HttpResponse httpResponse = null;
        OutputStream out = null;
        JSONObject result = new JSONObject();
        try {
            httpGet = new HttpGet(FinalURL.DOWN_URL);
            JSONObject object = RSAUtil.getReqHeard();
            httpGet.addHeader("fileName", uuid);
            httpGet.setHeader("X-SID", object.optString("data"));
            httpGet.setHeader("X-Signature", object.optString("sign"));
            httpGet.setHeader("publicKey", object.optString("publicKey"));
            httpResponse = httpClient.execute(httpGet);
            int status = httpResponse.getStatusLine().getStatusCode();
            result.put("status", status);
            if (status == 200) {
                HttpEntity entity = httpResponse.getEntity();
                in = entity.getContent();
                //下载的文件携带这个名称
                response.setHeader("Content-Disposition", "attachment;filename=" + uuid);
                response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
                response.addHeader("Pragma", "no-cache");
                //文件下载类型--二进制文件
                response.setContentType("application/octet-stream");
                response.setHeader("Set-Cookie", "fileDownload=true; path=/");
                out = response.getOutputStream();
                // 创建缓冲区
                byte buffer[] = new byte[1024];
                int len = 0;
                // 循环将输入流中的内容读取到缓冲区中
                while ((len = in.read(buffer)) != -1) {
                    // 输出缓冲区内容到浏览器，实现文件下载
                    out.write(buffer, 0, len);
                }
            } else if (status == 410) {
                response.addHeader("charset", "utf-8");
                result.put("msg", "资源已不存在！");
            } else if (status == 403) {
                response.addHeader("charset", "utf-8");
                result.put("msg", "非法请求！");
            } else {
                result.put("msg", "未知错误！");
            }
        } catch (Exception e) {
            logger.error("文件下载：" + e.getMessage());
        } finally {
            try {
                if (in != null)
                    // 关闭文件流
                    in.close();
                if (out != null) {
                    // 关闭输出流
                    out.flush();
                    out.close();
                }
                if (httpGet != null)
                    httpGet.clone();
            } catch (Exception e) {
                logger.error("关闭资源：" + e.getMessage());
            }
        }
        return result;
    }
}
